<?php defined('SYSPATH') OR die('No direct access allowed.');

require_once 'file.php';

class Image_Plugin extends File_Plugin {
	
	var $images = array();
	var $keep_original = FALSE;
	
	public function __construct($name='', $params=array())
	{
		parent::__construct($name, $params);
		
		if (empty($params['images'])) throw new Kohana_Exception(Kohana::lang('image_plugin.images_not_set'));
		$this->images = $params['images'];
		
		$this->type = isset($this->params['type']) ? $this->params['type'] : 'gif,jpg,png';
		
		$this->thumb_width = isset($this->params['thumb_width']) ? $this->params['thumb_width'] : 120;
		$this->thumb_height = isset($this->params['thumb_height']) ? $this->params['thumb_height'] : 120;
		
		$this->keep_original = isset($this->params['keep_original']) ? $this->params['keep_original'] : FALSE;
	}
	
	public function upload_file($file, $upload_values=null)
	{
		if ( ! is_string($orig_filename = parent::upload_file($file, $upload_values)) || $orig_filename=='""') return $orig_filename;
		
		$orig_basename = basename($orig_filename);
		
		$uploaded = 1;
		$failed = 0;
		
		foreach ($this->images as $num=>$img)
		{
			$file = Image::factory($orig_filename);
			
			if ( ! empty($img['width']) && ! empty($img['height']))
			{
				$img['method'] = isset($img['method']) ? $img['method'] : 'maxcrop';
				switch ($img['method'])
				{
					case 'resize':
						$file->resize($img['width'], $img['height'], isset($img['master_dim']) ? $img['master_dim'] : Image::AUTO);
						break;
					case 'crop':
						$file->resize($img['width'], $img['height'], isset($img['top']) ? $img['top'] : 'center', isset($img['left']) ? $img['left'] : 'center');
						break;
					case 'maxcrop':
					default:
						$file->maxcrop($img['width'], $img['height'], isset($img['force']) ? $img['force'] : TRUE, isset($img['top']) ? $img['top'] : 'center', isset($img['left']) ? $img['left'] : 'center');
						break;
				}
			}
			if (isset($img['rotate'])) $file->sharpen($img['rotate']);
			if (isset($img['flip'])) $file->sharpen($img['flip']);
			if (isset($img['sharpen'])) $file->sharpen($img['sharpen']);
			if (isset($img['quality'])) $file->sharpen($img['quality']);
			if (isset($img['watermark']) && Kohana::config('image.driver')=='GB')
			{
				$file->watermark
					(
						Image::factory($img['watermark']['file']),
						isset($img['watermark']['transparency']) ? $img['watermark']['transparency'] : 80,
						isset($img['watermark']['left']) ? $img['watermark']['left'] : null,
						isset($img['watermark']['top']) ? $img['watermark']['top'] : null
					);
			}
			
			$dir_base = isset($img['url_path']) ? $img['url_path'] : $this->directory;
			$dir = $this->get_dir($dir_base, $upload_values);
			if ( ! file_exists($dir)) mkdir($dir);
			$filename = isset($img['thumb_marker']) ?
				$this->thumb_marker($orig_basename, $img['thumb_marker']) :
				$orig_basename;
			
			if ($file->save($dir.$filename)) $uploaded++;
			else $failed++;
			
			//Kohana::log('info', 'File: '.$dir.$filename.', Failure: '.$failed.', Success: '.$uploaded);
		}
		
		if ($uploaded) Kohana::instance()->user_messages->add(Kohana::lang('image_plugin.file_uploaded',$uploaded));
		if ($failed) Kohana::instance()->user_messages->add(Kohana::lang('image_plugin.file_upload_failed',$failed));
		
		if ( ! $this->keep_original)
		{
			$dir = $this->get_dir(null, $upload_values);
			if (@unlink(DOCROOT.$dir.$orig_basename))
				Kohana::instance()->user_messages->add(Kohana::lang('image_plugin.delete_orig'));
			else
				Kohana::instance()->user_messages->add(Kohana::lang('image_plugin.delete_orig_failed'), 'error');
		}
		return $orig_filename;
	}
	
	public function delete_file($file=null, $delete_values=null)
	{
		if ($file==null)
		{
			$values = Kohana::instance()->wb_db->get_last_row();
			$file = isset($values[$this->name]) ? $values[$this->name] : null;
			$delete_values = empty($delete_values) ? $values : $delete_values;
		}
		if ( ! is_string($file)) return FALSE;
		elseif ($file=='') return '';
		
		$deleted = 0;
		$failed = 0;
		foreach ($this->images as $img)
		{
			$dir = $this->get_dir($img['url_path'], $delete_values);
			$filename = isset($img['thumb_marker']) ?
				$this->thumb_marker($file, $img['thumb_marker']) :
				$file;
			if (@unlink(DOCROOT.$dir.$filename)) $deleted++;
			else {
				Kohana::instance()->user_messages->add(DOCROOT.$this->get_dir($img['url_path']).$filename, 'alert');
				$failed++;
			}
		}
		
		if ($deleted>0)
			Kohana::instance()->user_messages->add(Kohana::lang('image_plugin.file_deleted',$deleted));
		
		if ($failed>0)
			Kohana::instance()->user_messages->add(Kohana::lang('image_plugin.file_delete_failed',$failed), 'error');
		
		if ($this->keep_original)
		{
			if ( @unlink(DOCROOT.$this->get_dir(null, $delete_values).$file)):
				Kohana::instance()->user_messages->add(Kohana::lang('image_plugin.delete_orig'));
			else:
				Kohana::instance()->user_messages->add(Kohana::lang('image_plugin.delete_orig_failed'), 'error');
				return FALSE;
			endif;
		}
		return $failed==0;
	}

	
	/**
	 * Renders the form element
	 * 
	 * @return string
	 */
	public function render_item()
	{
		$img = reset($this->images);
		$dir = isset($img['url_path']) ? $img['url_path'] : $this->directory;
		$dir = $this->get_dir($dir);
		
		$value = is_array($this->value) ? $this->value[$this->name] : $this->value;
			
		$str = $this->prefix;
		$str .= form::label($this->name, $this->label);
		$str .= form::upload($this->name, '', html::attributes($this->attributes));
		if ($value) 
		{
			$file = $dir.$value;
			$sizes = file_exists($file) ? getimagesize($file) : null;
			
			if (is_array($sizes))
			{
				$m = max($this->thumb_width/$sizes[0], $this->thumb_height/$sizes[1]);
				$w = floor($sizes[0] * $m);
				$h = floor($sizes[1] * $m);
				$alt = array('alt'=>$value, 'width'=>$w, 'height'=>$h);
			}
			else $alt = $value;
			
			$str .= '<span class="file_del">'.Kohana::lang('file_plugin.delete').' '.form::checkbox($this->name.'_del', $value).'</span>';
			$str .= '<span class="description">'.html::image($file, $alt, FALSE).'</span>';
		}
		$str .= $this->suffix;
		
		return $str;
	}
	
	public function render_cell()
	{
		$value = is_array($this->value) ? $this->value[$this->name] : $this->value;
		if ($value) 
		{
			$img = reset($this->images);
			$dir = isset($img['url_path']) ? $img['url_path'] : $this->directory;
			$file = $this->get_dir($dir).$value;
			$sizes = file_exists($file) ? getimagesize($file) : null;
			
			if (is_array($sizes))
			{
				$m = max($this->thumb_width/$sizes[0], $this->thumb_height/$sizes[1]);
				$w = floor($sizes[0] * $m);
				$h = floor($sizes[1] * $m);
				$alt = array('alt'=>$value, 'width'=>$w, 'height'=>$h);
			}
			else $alt = $value;
		}
		else $alt = '';
		return isset($file) ?  html::image($file, $alt) : '';
	}

	
	public function thumb_marker($old_name, $marker)
	{
		$ext = substr($old_name, strrpos($old_name, '.'));
		$base = substr($old_name, 0, -strlen($ext));
		
		return $base.$marker.$ext;
	}
	
}

//End of Image_Plugin Library